//
//  Helper.cpp
//  SkyFight
//
//  Created by HoangLinh on 7/25/13.
//
//

#include "Helper.h"
#include "ScreenManager.h"

CCDictionary* getAttributeDict(const xml_node *xmlNode)
{
    CCDictionary *attrDict = new CCDictionary();
    for (xml_attribute_iterator ait = xmlNode->attributes_begin(); ait != xmlNode->attributes_end(); ++ait) {
        attrDict->setObject(CCString::create(ait->value()), ait->name());
    }
    return attrDict;
}

CCDictionary* getAttributeDict(const xml_node_iterator xmlNode)
{
    CCDictionary *attrDict = new CCDictionary();
    for (xml_attribute_iterator ait = xmlNode->attributes_begin(); ait != xmlNode->attributes_end(); ++ait) {
        attrDict->setObject(CCString::create(ait->value()), ait->name());
    }
    return attrDict;
}

CCPoint getPosFromDict(CCDictionary *_dict, CCSize _objSize)
{
    return CCPointMake(_dict->valueForKey("x")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor + _objSize.width/2.f,
                       _dict->valueForKey("y")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor + _objSize.height/2.f);
}

CCSize getSizeFromDict(CCDictionary *_dict)
{
    return CCSizeMake(_dict->valueForKey("width")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor,
                       _dict->valueForKey("height")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor);
}

b2Vec2 getPosFromDict(CCDictionary *_dict)
{
    return b2Vec2(_dict->valueForKey("x")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor / PTM_RATIO,
                  _dict->valueForKey("y")->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor / PTM_RATIO);
}

float getRadiusFromDict(CCDictionary *_dict)
{
    return _dict->valueForKey(KEY_RADIUS)->floatValue() * ScreenManager::sharedScreenMan()->scaleFactor / PTM_RATIO;
}

float lengthOfVector(b2Vec2 vect)
{
    return sqrtf(vect.x * vect.x + vect.y * vect.y);
}

int randomFromTo(int _from, int _to)
{
    return (rand() % (_to - _from) + _from);
}

float frandomFromTo(float _from, float _to, int _fraction)
{
    int from = _from * _fraction;
    int to = _to * _fraction;

    return ((float)(rand() % (to - from) + from) / (float)_fraction);
}

b2Vec2 getVectorDirection(float x, float y)
{
    if (fabs(x) > 1 || fabs(y) > 1) {
        if (fabs(x) > fabs(y)) {
            y = y / fabs(x);
            x = x / fabs(x);
        } else {
            x = x / fabs(y);
            y = y / fabs(y);
        }
    }
    return b2Vec2(x, y);
}
